package hu.pixelesztergalyos.gui;

import java.io.IOException;

import hu.pixelesztergalyos.continuity.Game;
import hu.pixelesztergalyos.continuity.GameState;

//Timer class
public class Timer {
	public Game owner;                // the owner of the Timer class for communication purposes
	public View view;                 // view for displaying the communicated information
  public GameState gs;              // gs: handling the different gamestate (paused, mainmenu, ingame, etc)
  private long currentTime = 0;     // currentTime: updated time since application start
  private long oldTime = 0;         // oldTime: time saved at the last update
  private byte dt = 20;             // dt: interval between movement segments
  public boolean enabled = false;   // enabled: depending on gamestate preferences Timer either works or is stopped

	// constructor
	public Timer() {

	}

	/**
	 * This should be the onidle callback func
	 * 
	 * @return
	 * @throws InterruptedException
	 * @throws IOException 
	 */
	public void checkTime() throws InterruptedException, IOException {
		if (!enabled)
		{
			Thread.currentThread().sleep(dt);
			return;
		}
		if(gs == GameState.MAINMENU)  // if in mainmenu
		{
			this.enabled = false;       // Timer is disabled
			view.renderMainMenu();      // display mainmenu 
			return;
		}
		if(gs == GameState.PAUSEMENU)  // if in pausemenu
		{ 
			this.enabled = false;        // Timer is disabled
			view.renderPauseMenu();      // dispaly pausemenu
			return;
		}
		
		currentTime = System.nanoTime()/1000000;
		long elapsed_time = currentTime - oldTime;
		if (elapsed_time < dt) {
			int ms_to_wait = (int) (dt-elapsed_time);
			ms_to_wait -= 3;              //Assumes that game logic update + rendering won't last longer than 3 msecs
			if (ms_to_wait > 0) {
				Thread.currentThread().sleep(ms_to_wait);
			}
			return; // Less than 20 msecs passed, also no need for overwriting
			// old_time (cuz we go on waiting)
		}

		oldTime = currentTime; // More than dt ms passed, so we have to catch up
		float remaining;
		for (remaining = elapsed_time; remaining > dt; remaining -= dt) {
			owner.update(gs); // Step
		}

		oldTime -= remaining;
		
		view.vs = owner.getLevel().getViewState();
		view.render();
	}
	
	public void enable()
	{
		this.enabled = true;
		oldTime = System.nanoTime()/1000000;
	}

	/**
	 * 
	 * @return
	 */
	public long getCurrentTime() {
		return currentTime;
	}

	public void setdt(byte dt) {
		this.dt = dt;
	}

	/**
	 * 
	 * @return
	 */
	public long getOldTime() {
		return oldTime;
	}

	/**
	 * 
	 * @return
	 */
	public void setCurrentTime(long currentTime) {
		this.currentTime = currentTime;
	}

	/**
	 * 
	 * @return
	 */
	public void setOldTime(long oldTime) {
		this.oldTime = oldTime;
	}

}
